package mya.mes.mdc.internal.ui;

import freemarker.log.Logger;
import freemarker.template.*;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import jxl.write.Boolean;
import jxl.write.Number;
import mya.common.jaxrs.result.AddResult;
import mya.common.jaxrs.result.ListResult;
import mya.common.jpa.context.AbstractLogic;
import mya.common.jpa.context.AbstractQuery;
import mya.common.jpa.context.ServiceContext;
import mya.common.jpa.pagination.DataPage;
import mya.common.jpa.pagination.PageRange;
import mya.mes.mdc.constant.Sysconstant;
import mya.mes.mdc.local.mongodb.FilterDto;
import mya.mes.mdc.local.mongodb.MongoDbService;
import mya.mes.mdc.local.plc.PlcTagDefService;
import mya.mes.mdc.logic.plc.PlcTagDefServiceImpl;
import mya.mes.mdc.logic.tag.PlcTagCache;
import mya.mes.mdc.model.alarm.MdcAlarmType;
import mya.mes.mdc.model.system.TagType;
import mya.mes.mdc.mongodb.Mongo;
import mya.mes.mdc.mongodb.MongoDbServiceImpl;
import org.bson.Document;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Path("/{tenantId}/{loginId}/mdc/ui/")
public class MdcUi {


    private Logger log = Logger.getLogger(ExportMyWord.class.toString());
    private Configuration config = null;


    @PathParam("tenantId")
    private String tenantId;

    @PathParam("loginId")
    private Long loginId;

    @GET
    @Path("test/")
    public String get() {
        return "UI ok";
    }

    @GET
    @Path("tag/")
    @Produces("application/json")
    public ListResult queryProjectFile() {

        AbstractQuery query = new AbstractQuery(tenantId, loginId, true) {
            @Override
            protected DataPage process(ServiceContext serviceContext) throws Exception {

                PlcTagDefService alarmTypeService = new PlcTagDefServiceImpl();
                alarmTypeService.updateTags(serviceContext);
                return DataPage.emptyData(MdcAlarmType.class, PageRange.NOT_PAGE);
            }
        };

        return ListResult.result(query);
    }

    @POST
    @Path("queryTagValue")
    @Produces("application/json")
    public AddResult queryTagValue(List<FilterDto> dtos) {

        AbstractLogic logic = new AbstractLogic(tenantId, loginId) {
            @Override
            protected Object process(ServiceContext serviceContext) throws Exception {
                List<Document> dataList = new ArrayList<>();
                MongoDbService service = new MongoDbServiceImpl();
                dataList = service.queryMdcData(dtos, null);
                return dataList;
            }
        };
        return AddResult.result(logic);
    }

    @GET
    @Path("getDatabyLine")
    @Produces("application/json")
    public void getDatabyLine(@QueryParam("lineName") String lineName, @QueryParam("startTime") String startTime,
                              @QueryParam("endTime") String endTime, @QueryParam("interval") String interval) {
        lineName = "LINE3";//ceshi
        startTime = "2020-12-31 07:00";
        endTime = "2020-12-31 18:00";
        interval = "60";
        String[] dateArray = {};
        MongoDbService mongoDbService = Mongo.getInstance().getMongoDbService();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date startDate = simpleDateFormat.parse(startTime);
            Date endDate = simpleDateFormat.parse(endTime);
            Long space = endDate.getTime() - startDate.getTime();
            Long count = space / (Integer.parseInt(interval) * 60 * 1000) + 1;

            dateArray = new String[count.intValue()];
            int intervalTime = Integer.parseInt(interval);
            if (startDate.getTime() <= endDate.getTime()) {
                int i = 0;
                for (Long start = startDate.getTime(); start <= endDate.getTime(); start = (start + intervalTime * 60 * 1000), i++) {
                    dateArray[i] = simpleDateFormat.format(start);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Map<String, String> data = new HashMap<String, String>();
        if (dateArray != null) {
            for (int i = 0; i < dateArray.length; i++) {
//                List<Document> documents = mongoDbService.queryMdcDataByParameter("LINE3", "2020-12-03 13:30", "AI", "_id");
                List<Document> documents = mongoDbService.queryMdcDataByParameter("LINE3", dateArray[i], "AI", "_id");
//                List<Document> documents = mongoDbService.queryMdcReportDataByParameter(dateArray[i], "_id");
                if (documents != null && documents.size() > 0) {
                    String time = dateArray[i].split(" ")[1].split(":")[0];
                    String pre = "";
                    if (Sysconstant.T_7.equals(time)) {
                        pre = Sysconstant.T_7;
                    } else if (Sysconstant.T_8.equals(time)) {
                        pre = Sysconstant.T_8;
                    } else if (Sysconstant.T_9.equals(time)) {
                        pre = Sysconstant.T_9;
                    } else if (Sysconstant.T_10.equals(time)) {
                        pre = Sysconstant.T_10;
                    } else if (Sysconstant.T_11.equals(time)) {
                        pre = Sysconstant.T_11;
                    } else if (Sysconstant.T_12.equals(time)) {
                        pre = Sysconstant.T_12;
                    } else if (Sysconstant.T_13.equals(time)) {
                        pre = Sysconstant.T_13;
                    } else if (Sysconstant.T_14.equals(time)) {
                        pre = Sysconstant.T_14;
                    } else if (Sysconstant.T_15.equals(time)) {
                        pre = Sysconstant.T_15;
                    } else if (Sysconstant.T_16.equals(time)) {
                        pre = Sysconstant.T_16;
                    } else if (Sysconstant.T_17.equals(time)) {
                        pre = Sysconstant.T_17;
                    } else if (Sysconstant.T_18.equals(time)) {
                        pre = Sysconstant.T_18;
                    }
                    Document doc = documents.get(0);
                    for (String key : doc.keySet()) {
                        String value = doc.get(key).toString();
                        System.out.println(key + ":" + value);
                        data.put(pre + key, value);
                    }
                }
            }
        }

        List<Document> documents = mongoDbService.queryMdcDataByParameter("LINE3", "2020-12-03 13:30", "AI", "_id");
        if (documents != null && documents.size() > 0) {
            System.out.println("size:" + documents.size());
        }

        return;
    }

    @GET
    @Path("/downFile")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response getAll(@QueryParam("filePath") String filePath) throws IOException {

        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("lineName", "3号线");
        dataMap.put("ab", "");
        dataMap.put("abcd", "");
        File file = null;
        Response response = null;
        try {
            file = ExportMyWord.createWord(dataMap, "module.ftl", "E:/Line3.doc");
            System.out.println(file.getName());
            response = Response
                    .ok(file)
                    .header("Content-disposition", "attachment;filename=" + URLEncoder.encode("产线数据.doc", "UTF-8"))
                    .header("ContentType", "application/msword")
                    .header("Cache-Control", "no-cache").build();
        } catch (Exception e) {

        } finally {
            if (file != null && file.exists()) {
                file.delete();
            }
        }
        return response;
    }

    @GET
    @Path("/downFile_")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public HttpServletResponse getAll_(@QueryParam("filePath") String filePath, @Context HttpServletResponse response_) throws IOException {

        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("lineName", "3号线");
        dataMap.put("abcd", "444");
        File file = null;
        try {
            file = ExportMyWord.createWord(dataMap, "module.ftl", "E:/Line3.doc");
            System.out.println(file.getName());
        } catch (Exception e) {

        } finally {

        }
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response_.reset();
        // 设置response的Header
        response_.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("产线数据.doc", "UTF-8"));
        response_.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response_.getOutputStream());
        response_.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        if (file != null && file.exists()) {
            file.delete();
        }
        return response_;
    }

    /**
     * 根据厂线 时间导出参数表
     *
     * @param lineName
     * @param startTime
     * @param endTime
     * @param interval
     * @param response_
     * @return
     * @throws IOException
     */
    @GET
    @Path("/downDataFile")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public HttpServletResponse getDatabyLine_(@QueryParam("lineName") String lineName, @QueryParam("startTime") String startTime,
                                              @QueryParam("endTime") String endTime, @QueryParam("interval") String interval, @Context HttpServletResponse response_) throws IOException {
//        lineName = "LINE3";
        startTime = "2020-12-31 07:00";
        endTime = "2020-12-31 18:00";
        interval = "60";
        String[] dateArray = {};
        MongoDbService mongoDbService = Mongo.getInstance().getMongoDbService();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date startDate = simpleDateFormat.parse(startTime);
            Date endDate = simpleDateFormat.parse(endTime);
            Long space = endDate.getTime() - startDate.getTime();
            Long count = space / (Integer.parseInt(interval) * 60 * 1000) + 1;

            dateArray = new String[count.intValue()];
            int intervalTime = Integer.parseInt(interval);
            if (startDate.getTime() <= endDate.getTime()) {
                int i = 0;
                for (Long start = startDate.getTime(); start <= endDate.getTime(); start = (start + intervalTime * 60 * 1000), i++) {
                    dateArray[i] = simpleDateFormat.format(start);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Map<String, String> data = new HashMap<String, String>();
        if (dateArray != null) {
            for (int i = 0; i < dateArray.length; i++) {
                List<Document> documents = mongoDbService.queryMdcDataByParameter(lineName, dateArray[i], "AI", "_id");
                if (documents != null && documents.size() > 0) {
                    String time = dateArray[i].split(" ")[1].split(":")[0];
                    String pre = "";
                    if (Sysconstant.T_1.equals(time)) {
                        pre = Sysconstant.T_1;
                    } else if (Sysconstant.T_2.equals(time)) {
                        pre = Sysconstant.T_2;
                    } else if (Sysconstant.T_3.equals(time)) {
                        pre = Sysconstant.T_3;
                    } else if (Sysconstant.T_4.equals(time)) {
                        pre = Sysconstant.T_4;
                    } else if (Sysconstant.T_5.equals(time)) {
                        pre = Sysconstant.T_5;
                    } else if (Sysconstant.T_6.equals(time)) {
                        pre = Sysconstant.T_6;
                    } else if (Sysconstant.T_7.equals(time)) {
                        pre = Sysconstant.T_7;
                    } else if (Sysconstant.T_8.equals(time)) {
                        pre = Sysconstant.T_8;
                    } else if (Sysconstant.T_9.equals(time)) {
                        pre = Sysconstant.T_9;
                    } else if (Sysconstant.T_10.equals(time)) {
                        pre = Sysconstant.T_10;
                    } else if (Sysconstant.T_11.equals(time)) {
                        pre = Sysconstant.T_11;
                    } else if (Sysconstant.T_12.equals(time)) {
                        pre = Sysconstant.T_12;
                    } else if (Sysconstant.T_13.equals(time)) {
                        pre = Sysconstant.T_13;
                    } else if (Sysconstant.T_14.equals(time)) {
                        pre = Sysconstant.T_14;
                    } else if (Sysconstant.T_15.equals(time)) {
                        pre = Sysconstant.T_15;
                    } else if (Sysconstant.T_16.equals(time)) {
                        pre = Sysconstant.T_16;
                    } else if (Sysconstant.T_17.equals(time)) {
                        pre = Sysconstant.T_17;
                    } else if (Sysconstant.T_18.equals(time)) {
                        pre = Sysconstant.T_18;
                    } else if (Sysconstant.T_19.equals(time)) {
                        pre = Sysconstant.T_19;
                    } else if (Sysconstant.T_20.equals(time)) {
                        pre = Sysconstant.T_20;
                    } else if (Sysconstant.T_21.equals(time)) {
                        pre = Sysconstant.T_21;
                    } else if (Sysconstant.T_22.equals(time)) {
                        pre = Sysconstant.T_22;
                    } else if (Sysconstant.T_23.equals(time)) {
                        pre = Sysconstant.T_23;
                    } else if (Sysconstant.T_24.equals(time)) {
                        pre = Sysconstant.T_24;
                    }
                    Document doc = documents.get(0);
                    for (String key : doc.keySet()) {
                        String value = doc.get(key).toString();
                        System.out.println(pre + key + ":" + value);
                        TagType tagType = PlcTagCache.getInstance().getTagTypes().get(key);
                        if (tagType != null && tagType.getRate() != null) {
                            BigDecimal b1 = new BigDecimal(Integer.parseInt(value));
                            BigDecimal b2 = new BigDecimal(tagType.getRate());
                            value = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP).toString();
                        }
                        data.put(pre + "_" + key, value);
                    }
                }
            }
        }

        data.put("line", lineName);
        data.put("l4_z1_c_2", "20");
        data.put("l4_z1_c_3", "20");
        data.put("l4_z1_c_4", "20");
        File file = null;
        String ftl = "";
        if (Sysconstant.LINE_1.equals(lineName) || Sysconstant.LINE_3.equals(lineName) || Sysconstant.LINE_5.equals(lineName)) {
            ftl = Sysconstant.FTL_3;
        } else if (Sysconstant.LINE_2.equals(lineName) || Sysconstant.LINE_4.equals(lineName)) {
            ftl = Sysconstant.FTL_4;
        } else if (Sysconstant.LINE_6.equals(lineName)) {
            ftl = Sysconstant.FTL_6;
        } else {

        }
        try {
            file = ExportMyWord.createWord(data, ftl, "E:/Line.xls");
            System.out.println(file.getName());
        } catch (Exception e) {

        } finally {

        }
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response_.reset();
        // 设置response的Header
        response_.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(lineName + "产线数据.xls", "UTF-8"));
        response_.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response_.getOutputStream());
        response_.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        if (file != null && file.exists()) {
            file.delete();
        }
        return response_;

    }


}
